#include "stdafx.hpp"
#include "ColligereLogDialog.hpp"
#include "ColligereApp.hpp"
#include "ColligereConfigHandler.hpp"
#include "ColligereIds.hpp"

/////////////////////////////////////////////////
// ColligereHtmlLog
/////////////////////////////////////////////////

col::HtmlLog::HtmlLog ( wxSimpleHtmlListBox *pLogTarget ) : mpLogTarget ( pLogTarget ) 
{
	wxASSERT ( mpLogTarget );
}

void col::HtmlLog::DoLog ( wxLogLevel level, const wxString &rMsg, time_t time )
{
	using namespace boost;
	using namespace std;

	wxASSERT ( mpLogTarget );

	const wxString time_str ( wxDateTime ( time ).Format ( "%c", wxDateTime::Local ) );

	switch ( level )
	{
	case wxLOG_Error:
		mpLogTarget->Append ( str ( format ( "<p><font color=\"#b05858\">[%1%]"\
			"<b> Error:</b></font> %2%</p>")  % time_str % rMsg ) );
		break;
	case wxLOG_Warning:
		mpLogTarget->Append ( str ( format ( "<p><font color=\"#d5924a\">[%1%]"\
			"<b> Warning:</b></font> %2%</p>") % time_str % rMsg ) );
		break;
	case wxLOG_Debug:
		mpLogTarget->Append ( str ( format ( "<p><font color=\"#888888\">[%1%]"\
			"<b> Debug:</b></font> %2%</p>") % time_str % rMsg ) );
		break;
	default:
		mpLogTarget->Append ( str ( format ( "<p><font color=\"#888888\">[%1%]"\
			"<b> Information:</b></font> %2%</p>") % time_str % rMsg ) );
		break;
	}
}

/////////////////////////////////////////////////
// ColligereLogDialog
/////////////////////////////////////////////////

col::LogDialog::LogDialog ( wxFrame *pParent )
{
	wxXmlResource::Get()->LoadDialog ( this, pParent, "ID_Dialog_Log" );

	mpLogCtrl = XRCCTRL ( *this, "ID_HtmlListBox_Log", wxSimpleHtmlListBox );
	mpLogCtrl->SetBackgroundColour ( wxColour ( 249, 248, 244 ) );

	wxIcon log;
	log.CopyFromBitmap ( wxGetApp().GetIcon ( App::IconIndex::Log ) );
	wxASSERT ( log.IsOk() );
	SetIcon ( log );

	ConnectEventHandlers();

	ResetLog();
}

void col::LogDialog::ConnectEventHandlers()
{
	Bind ( wxEVT_COMMAND_BUTTON_CLICKED,
		&LogDialog::OnButtonOk, XRCID ( "wxID_CANCEL" ) );
	Bind ( wxEVT_COMMAND_BUTTON_CLICKED,
		&LogDialog::OnButtonClearLog, XRCID ( "ID_Button_ClearLog" ) );
	Bind ( wxEVT_COMMAND_BUTTON_CLICKED,
		&LogDialog::OnButtonSaveLogAs, XRCID ( "ID_Button_SaveLogAs" ) );
	Bind ( wxEVT_CLOSE_WINDOW, &LogDialog::OnClose, GetId() );
}

void col::LogDialog::ResetLog()
{
	using namespace boost;
	using namespace std;

	mpLogCtrl->Clear();
}

void col::LogDialog::SaveLog ( const wxString &rFile )
{
	using namespace boost;
	wxString log_file;

	if ( rFile.empty() )
	{
		log_file = str ( format ( "ColligereLog-%1%.htm" ) % 
		wxDateTime::Today().FormatISODate() );
	}
	else
	{
		log_file = rFile;
	}
	wxFile out ( log_file, wxFile::write );

	if ( out.IsOpened() )
	{
		out.Write ( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 "\
                "Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html>"\
                "<head><meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">"\
                "<title>Colligere Log</title></head>" );

        const wxString wxver ( wxVERSION_STRING );

        out.Write ( str ( format ( "<body bgcolor=\"#f9f8f4\">"\
                "<h2>%1% Log (%2%)</h2><b>System Information:</b><br><br>%3%<br>"\
                "SQLite %4%<br>%5%<br><br>Compiled On %6%<br>Running Under "\
                "Debugger: %7%<br>Running Under 64bit System: %8%<br>System Endian-ness: "\
                "%9%<br>Amount of Free Memory: %10% bytes<br><br><b>Log Events:</b><br>") % 
                wxGetApp().GetVersioString() % wxDateTime::Now().Format 
                ( "%c" ) % wxGetOsDescription() % wxSQLite3Database::GetVersion() % 
                wxver % __TIMESTAMP__ % ( wxIsDebuggerRunning() ? _("Yes") : _("No") ) % 
                ( wxIsPlatform64Bit() ? _("Yes") : _("No") ) % 
                ( wxIsPlatformLittleEndian() ? "Little Endian" : "Big Endian") %
                wxGetFreeMemory() ) );

		wxArrayString labels  ( mpLogCtrl->GetStrings() );
		for ( wxUint32 i = 0; i < labels.size(); ++i )
		{
			out.Write ( labels[i] );
		}
		out.Write ( "</body></html>" );
		out.Close();
	}
}

////////////////////////////////
// Event handler
////////////////////////////////

void col::LogDialog::OnButtonClearLog ( wxCommandEvent & )
{
	ResetLog();
}

void col::LogDialog::OnButtonSaveLogAs ( wxCommandEvent & )
{
	using namespace boost;
	using namespace std;

	wxFileDialog dlg ( this, _("Choose a file"), empty_string, empty_string, 
		_( "All Files (*.*)|*.*|Text files (*.txt)|*.txt" ), wxFD_SAVE | 
		wxFD_OVERWRITE_PROMPT );

	ConfigHandler::Get().LoadLastDirectory ( ConfigVariable::LastSavedLogDir, dlg );

	dlg.SetFilename ( str ( format ( "ColligereLog-%1%.htm") % 
		wxDateTime::Today().FormatISODate() ) );

	if ( dlg.ShowModal() == wxID_OK )
	{
		SaveLog ( dlg.GetPath() );

		ConfigHandler::Get().SetValue ( ConfigVariable::LastSavedLogDir, 
			wxFileName ( dlg.GetPath() ).GetPath ( wxPATH_GET_SEPARATOR | 
			wxPATH_GET_VOLUME ) );
	}
}

void col::LogDialog::OnButtonOk ( wxCommandEvent & )
{
	wxCommandEvent menu_check ( wxEVT_COMMAND_MENU_SELECTED, ID_Menu_ViewLog );
	GetParent()->GetEventHandler()->ProcessEvent ( menu_check );
}

void col::LogDialog::OnClose ( wxCloseEvent &rEvent )
{
	if ( rEvent.CanVeto() )
	{
		wxCommandEvent dumb;
		OnButtonOk ( dumb );
		rEvent.Veto();
	}
	else
	{
		rEvent.Skip();
	}
}